#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QDateTime>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow) {
    ui->setupUi(this);
    addSerialPortsToComboBox();  // 初始化串口列表

    // 连接串口的 readyRead 信号到 readSerialData 槽函数
    connect(&serialPort, &QSerialPort::readyRead, this, &MainWindow::readSerialData);

    // 连接 checkBox 的状态改变信号到槽函数
    connect(ui->checkBox_2, &QCheckBox::stateChanged, this, [this](int state) {
        receivePaused = (state == Qt::Checked);
    });

    // 初始化换行定时器
    newlineTimer = new QTimer(this);
    newlineTimer->setInterval(100);  // 100ms
    connect(newlineTimer, &QTimer::timeout, this, &MainWindow::checkForNewLine);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::addSerialPortsToComboBox() {
    ui->comboBox->clear();
    QList<QSerialPortInfo> serialPorts = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info : serialPorts) {
        ui->comboBox->addItem(info.portName() + " - " + info.description());
    }

    // 初始化波特率选项
    ui->comboBox_2->clear();
    ui->comboBox_2->addItems({"9600", "19200", "38400", "57600", "115200"});

    // 初始化数据位选项
    ui->comboBox_3->clear();
    ui->comboBox_3->addItems({"5", "6", "7", "8"});

    // 初始化校验位选项
    ui->comboBox_4->clear();
    ui->comboBox_4->addItems({"无校验", "偶校验", "奇校验"});

    // 初始化停止位选项
    ui->comboBox_5->clear();
    ui->comboBox_5->addItems({"1", "1.5", "2"});
}

void MainWindow::on_pushButton_clicked() {
    if (!serialPort.isOpen()) {
        // 获取用户选择的串口名称
        QString selectedPort = ui->comboBox->currentText().split(" - ").first();

        // 获取用户选择的波特率
        int baudRate = ui->comboBox_2->currentText().toInt();

        // 获取用户选择的数据位
        QSerialPort::DataBits dataBits;
        QString selectedDataBits = ui->comboBox_3->currentText();
        if (selectedDataBits == "5") dataBits = QSerialPort::Data5;
        else if (selectedDataBits == "6") dataBits = QSerialPort::Data6;
        else if (selectedDataBits == "7") dataBits = QSerialPort::Data7;
        else if (selectedDataBits == "8") dataBits = QSerialPort::Data8;
        else dataBits = QSerialPort::Data8;  // 默认值为 8 位

        // 获取用户选择的校验位
        QSerialPort::Parity parity;
        QString selectedParity = ui->comboBox_4->currentText();
        if (selectedParity == "无校验") parity = QSerialPort::NoParity;
        else if (selectedParity == "偶校验") parity = QSerialPort::EvenParity;
        else if (selectedParity == "奇校验") parity = QSerialPort::OddParity;
        else parity = QSerialPort::NoParity;  // 默认值为无校验

        // 获取用户选择的停止位
        QSerialPort::StopBits stopBits;
        QString selectedStopBits = ui->comboBox_5->currentText();
        if (selectedStopBits == "1") stopBits = QSerialPort::OneStop;
        else if (selectedStopBits == "1.5") stopBits = QSerialPort::OneAndHalfStop;
        else if (selectedStopBits == "2") stopBits = QSerialPort::TwoStop;
        else stopBits = QSerialPort::OneStop;  // 默认值为 1 位停止位

        // 配置串口参数
        serialPort.setPortName(selectedPort);
        serialPort.setBaudRate(baudRate);
        serialPort.setDataBits(dataBits);
        serialPort.setParity(parity);
        serialPort.setStopBits(stopBits);

        // 尝试打开串口
        if (serialPort.open(QIODevice::ReadWrite)) {
            QMessageBox::information(this, "连接成功", "串口已成功打开！");
            ui->pushButton->setText("关闭串口");  // 修改按钮名称
        } else {
            QMessageBox::critical(this, "连接失败", "无法打开串口，请检查串口名称和参数是否正确！");
        }
    } else {
        // 如果串口已经打开，则关闭串口
        serialPort.close();
        QMessageBox::information(this, "关闭成功", "串口已成功关闭！");
        ui->pushButton->setText("打开串口");  // 修改按钮名称
    }
}

void MainWindow::readSerialData() {
    if (receivePaused) {
        // 如果暂停显示接收内容，则将数据存储到缓冲区
        receiveBuffer.append(serialPort.readAll());
    } else {
        // 如果未暂停显示接收内容，则直接处理接收到的数据
        QByteArray data = serialPort.readAll();
        receiveBuffer.append(data);
        lastTimestamp = QDateTime::currentDateTime();  // 更新时间戳
        newlineTimer->start();  // 启动定时器
    }
}

void MainWindow::processReceivedData() {
    QString displayData;

    if (ui->checkBox->isChecked()) {
        // 如果勾选了16进制显示
        QByteArray hexData = receiveBuffer.toUtf8();  // 将 QString 转换为 QByteArray
        displayData = hexData.toHex().toUpper();      // 转换为十六进制并转为大写
    } else {
        // 如果未勾选16进制显示
        displayData = receiveBuffer;
    }

    if (ui->checkBox_4->isChecked()) {
        // 如果勾选了加入时间戳
        QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz");
        displayData = timestamp + " " + displayData;
    }

    updateReceiveArea(displayData);

    receiveBuffer.clear();  // 清空缓冲区
}

void MainWindow::checkForNewLine() {
    newlineTimer->stop();  // 停止定时器

    if (!receiveBuffer.isEmpty()) {
        processReceivedData();  // 处理缓冲区中的数据
    }
}

void MainWindow::updateReceiveArea(const QString &data) {
    if (ui->checkBox_3->isChecked()) {
        // 如果勾选了自动换行
        ui->plainTextEdit->appendPlainText(data);
    } else {
        // 如果未勾选自动换行
        ui->plainTextEdit->insertPlainText(data);
    }
}
